package cn.dgiot.fd.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyun.oss.common.utils.StringUtils;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.BatchCheckDeviceNamesRequest;
import com.aliyuncs.iot.model.v20180120.BatchCheckDeviceNamesResponse;
import com.aliyuncs.iot.model.v20180120.BatchQueryDeviceDetailRequest;
import com.aliyuncs.iot.model.v20180120.BatchQueryDeviceDetailResponse;
import com.aliyuncs.iot.model.v20180120.BatchRegisterDeviceWithApplyIdRequest;
import com.aliyuncs.iot.model.v20180120.BatchRegisterDeviceWithApplyIdResponse;
import com.aliyuncs.iot.model.v20180120.DeleteDeviceRequest;
import com.aliyuncs.iot.model.v20180120.DeleteDeviceResponse;
import com.aliyuncs.iot.model.v20180120.DisableThingRequest;
import com.aliyuncs.iot.model.v20180120.DisableThingResponse;
import com.aliyuncs.iot.model.v20180120.EnableThingRequest;
import com.aliyuncs.iot.model.v20180120.EnableThingResponse;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceRequest;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceResponse;
import com.aliyuncs.iot.model.v20180120.InvokeThingsServiceRequest;
import com.aliyuncs.iot.model.v20180120.InvokeThingsServiceResponse;
import com.aliyuncs.iot.model.v20180120.QueryBatchRegisterDeviceStatusRequest;
import com.aliyuncs.iot.model.v20180120.QueryBatchRegisterDeviceStatusResponse;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDesiredPropertyRequest;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDesiredPropertyResponse;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailRequest;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailResponse;
import com.aliyuncs.iot.model.v20180120.QueryDevicePropertyStatusRequest;
import com.aliyuncs.iot.model.v20180120.QueryDevicePropertyStatusResponse;
import com.aliyuncs.iot.model.v20180120.QueryDeviceRequest;
import com.aliyuncs.iot.model.v20180120.QueryDeviceResponse;
import com.aliyuncs.iot.model.v20180120.RegisterDeviceRequest;
import com.aliyuncs.iot.model.v20180120.RegisterDeviceResponse;
import com.aliyuncs.iot.model.v20180120.ResetThingRequest;
import com.aliyuncs.iot.model.v20180120.ResetThingResponse;
import com.aliyuncs.iot.model.v20180120.SetDeviceDesiredPropertyRequest;
import com.aliyuncs.iot.model.v20180120.SetDeviceDesiredPropertyResponse;
import com.aliyuncs.iot.model.v20180120.SetDevicePropertyRequest;
import com.aliyuncs.iot.model.v20180120.SetDevicePropertyResponse;

import cn.dgiot.fd.contant.AliyunConfig;
import cn.dgiot.fd.contant.DeviceStateEnum;
import cn.dgiot.fd.model.DeviceModel;
import cn.dgiot.fd.model.DeviceStateModel;
import cn.dgiot.fd.model.PropertiesSetFlowModel;
import cn.dgiot.fd.model.PropertiesSetModel;
import cn.dgiot.fd.service.IDeviceService;
import cn.dgiot.fd.service.IDeviceStateService;
import cn.dgiot.fd.service.IPropertiesSetFlowService;
import cn.dgiot.fd.service.IPropertiesSetService;

/**
 * [设备相关api调用]
 * @author
 *
 */
@Service
public class DeviceByAliyunImpl extends BaseServiceImpl implements IDeviceService {

	@Autowired
	private AliyunConfig aliyunConfig;
	
	@Autowired
	private IDeviceStateService deviceStateService;

	@Autowired
	private IPropertiesSetService propertiesSetService;
	
	@Autowired
	private IPropertiesSetFlowService propertiesSetFlowService;
	
	private Logger logger = LoggerFactory.getLogger(DeviceByAliyunImpl.class);


	@Override
	public RegisterDeviceResponse registerDevice(DeviceModel deviceModel) {
		
		RegisterDeviceResponse response = new RegisterDeviceResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** LoRaWAN设备的DevEUI*/
		String devEui = deviceModel.getDevEui();
		/** LoRaWAN设备的PIN Code */
		String pinCode = deviceModel.getPinCode();
		/** 设备设置备注名称 */
		String nickName = deviceModel.getNickName();
		
		if(StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("设备名称不能为空（可以使用IMEI号）");
			return response;
		}
		RegisterDeviceRequest request = new RegisterDeviceRequest();
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setDevEui(devEui);
		request.setPinCode(pinCode);
		request.setNickname(nickName);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			if(response != null && response.getSuccess()) {
				/** 创建成功后将设备添加到设备状态表中 */
				DeviceStateModel deviceStateModel = new DeviceStateModel();
				deviceStateModel.setIotId(response.getData().getIotId());
				deviceStateModel.setProductKey(response.getData().getProductKey());
				deviceStateModel.setDeviceName(response.getData().getDeviceName());
				deviceStateModel.setDeviceSecret(response.getData().getDeviceSecret());
				deviceStateModel.setState(DeviceStateEnum.NOT_ACTIVE.getCode());
				deviceStateService.insertDeviceState(deviceStateModel);
			}
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("设备注册失败");
			logger.error("-----------设备注册异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("设备注册失败");
			logger.error("-----------设备注册异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}
	
	

	@Override
	public QueryDeviceDetailResponse queryDeviceDetail(DeviceModel deviceModel) {
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** 设备id */
		String iotId = deviceModel.getIotId();
		QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
		QueryDeviceDetailResponse response = new QueryDeviceDetailResponse();
		
		if(StringUtils.isNullOrEmpty(iotId)
				&& StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者deviceName不为空");
			return response;
		}

		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setIotId(iotId);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			logger.info(response.getSuccess().toString());
			logger.info(response.getErrorMessage());
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询设备详情异常");
			logger.error("-----------查询设备详情异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询设备详情异常");
			logger.error("-----------查询设备详情异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public DeleteDeviceResponse deleteDevice(DeviceModel deviceModel) { 
		
		DeleteDeviceResponse response = new DeleteDeviceResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey; 
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** 设备id */
		String iotId = deviceModel.getIotId();
		DeleteDeviceRequest request = new DeleteDeviceRequest();
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		  
		if(StringUtils.isNullOrEmpty(iotId)
				&& StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者deviceName不为空");
			return response;
		}
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setIotId(iotId);
		
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			if(response != null && response.getSuccess()) {
				/** 创建成功后将设备添加到设备状态表中 */
				DeviceStateModel deviceStateModel = new DeviceStateModel();
				deviceStateModel.setProductKey(productKey);
				deviceStateModel.setDeviceName(deviceName);
				deviceStateService.deleteDeviceState(deviceStateModel);
			}
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("删除设备失败");
			logger.error("-----------删除设备异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("删除设备失败");
			logger.error("-----------删除设备异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public RegisterDeviceResponse updateDevice(DeviceModel deviceModel) {
		/** 原有设备名称 */
		String originalDeviceName = deviceModel.getOriginalDeviceName();
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		RegisterDeviceResponse registerDeviceResponse = new RegisterDeviceResponse();
		
		if(StringUtils.isNullOrEmpty(deviceName)) {
			registerDeviceResponse.setSuccess(false);
			registerDeviceResponse.setErrorMessage("设备名称不能为空");
			return registerDeviceResponse;
		}
		
		if(!StringUtils.isNullOrEmpty(originalDeviceName)) {
			// 只修改属性
			deviceModel.setDeviceName(originalDeviceName);	
		}
		// 先删除原有设备
		DeleteDeviceResponse deleteDeviceResponse = deleteDevice(deviceModel);
		if(deleteDeviceResponse.getSuccess()) {
			deviceModel.setDeviceName(deviceName);	
			registerDeviceResponse = registerDevice(deviceModel);
		}else {
			registerDeviceResponse.setSuccess(false);
			registerDeviceResponse.setErrorMessage("设备修改失败");
			return registerDeviceResponse;
		}
		
		return registerDeviceResponse;
	}

	@Override
	public BatchQueryDeviceDetailResponse batchQueryDeviceDetail(DeviceModel deviceModel) {
		String productKey = aliyunConfig.productKey;
		List<String> deviceNames = deviceModel.getDeviceNames();
		BatchQueryDeviceDetailRequest request = new BatchQueryDeviceDetailRequest();
		request.setProductKey(productKey);
		request.setDeviceNames(deviceNames);
		BatchQueryDeviceDetailResponse response = new BatchQueryDeviceDetailResponse();
		if(deviceNames != null && (deviceNames.size()==0 || deviceNames.size() > 100)) {
			response.setSuccess(false);
			response.setErrorMessage("设备名称不能为空且不能超过100个");
			return response;
		}
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("批量查询设备详情失败");
			logger.error("-----------批量查询设备详情异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("批量查询设备详情失败");
			logger.error("-----------批量查询设备详情异常--------------------------",e);
		}
		
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, StringUtils.join(",",deviceNames), response.getSuccess());
		return response;
	}

	@Override
	public QueryDeviceResponse queryDevice(DeviceModel deviceModel) {
		String productKey = aliyunConfig.productKey;
		String deviceName = deviceModel.getDeviceName();
		QueryDeviceResponse response = new QueryDeviceResponse();
		
		if(StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("设备名称不能为空");
			return response;
		}
		
		QueryDeviceRequest request = new QueryDeviceRequest();
		request.setProductKey(productKey);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询设备失败");
			logger.error("-----------查询设备异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询设备失败");
			logger.error("-----------查询设备异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public DisableThingResponse disableThing(DeviceModel deviceModel) {
		String productKey = aliyunConfig.productKey;
		String deviceName = deviceModel.getDeviceName();
		String iotId = deviceModel.getIotId();
		DisableThingRequest request = new DisableThingRequest();
		DisableThingResponse response = new DisableThingResponse();
		
		if(StringUtils.isNullOrEmpty(iotId)
				&& StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者deviceName不为空");
			return response;
		}
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setIotId(iotId);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			if(response != null && response.getSuccess()) {
				QueryDeviceDetailResponse queryDeviceDetailResponse = queryDeviceDetail(deviceModel);
				DeviceStateModel deviceStateModel = new DeviceStateModel();
	        	deviceStateModel.setProductKey(productKey);
	        	deviceStateModel.setDeviceName(queryDeviceDetailResponse.getData().getDeviceName());
	        	deviceStateModel.setState(queryDeviceDetailResponse.getData().getStatus());
	        	deviceStateService.updateDeviceState(deviceStateModel);
			}
			logger.info(response.getSuccess().toString());
			logger.info(response.getErrorMessage());
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("禁用设备失败");
			logger.error("-----------禁用设备异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("禁用设备失败");
			logger.error("-----------禁用设备异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public EnableThingResponse enableThing(DeviceModel deviceModel) {
		String productKey = aliyunConfig.productKey;
		String deviceName = deviceModel.getDeviceName();
		String iotId = deviceModel.getIotId();
		EnableThingRequest request = new EnableThingRequest(); 
		EnableThingResponse response = new EnableThingResponse();
	 
		if(StringUtils.isNullOrEmpty(iotId)
				&& StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者deviceName不为空");
			return response;
		}
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setIotId(iotId);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			if(response != null && response.getSuccess()) {
				QueryDeviceDetailResponse queryDeviceDetailResponse = queryDeviceDetail(deviceModel);
				DeviceStateModel deviceStateModel = new DeviceStateModel();
	        	deviceStateModel.setProductKey(productKey);
	        	deviceStateModel.setDeviceName(queryDeviceDetailResponse.getData().getDeviceName());
	        	deviceStateModel.setState(queryDeviceDetailResponse.getData().getStatus());
	        	deviceStateService.updateDeviceState(deviceStateModel);
			}
			logger.info(response.getSuccess().toString());
			logger.info(response.getErrorMessage());
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("启用设备失败");
			logger.error("-----------启用设备异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("启用设备失败");
			logger.error("-----------启用设备异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}
	
	@Override
	public ResetThingResponse resetThing(DeviceModel deviceModel) {
		String productKey = aliyunConfig.productKey;
		String deviceName = deviceModel.getDeviceName();
		String iotId = deviceModel.getIotId();
		ResetThingRequest request = new ResetThingRequest(); 
		ResetThingResponse response = new ResetThingResponse();
	 
		if(StringUtils.isNullOrEmpty(iotId)
				&& StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者deviceName不为空");
			return response;
		}
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setIotId(iotId);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("重置设备失败");
			logger.error("-----------重置设备异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("重置设备失败");
			logger.error("-----------重置设备异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public SetDevicePropertyResponse setDeviceProperty(PropertiesSetModel propertiesSetModel) {
		
		SetDevicePropertyResponse response = new SetDevicePropertyResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = propertiesSetModel.getDeviceName();
		/** 属性值 */
		String items = propertiesSetModel.toJSON();
		/** 物联网设备唯一标识 */
		String iotId = propertiesSetModel.getIotId();
		
		if(StringUtils.isNullOrEmpty(iotId)  && StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请确保iotId或deviceName不为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(items)) {
			response.setSuccess(false);
			response.setErrorMessage("items不能为空");
			return response;
		}
		
		SetDevicePropertyRequest request = new SetDevicePropertyRequest();
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setItems(items);
		request.setIotId(iotId);
		
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			if(response != null && response.getSuccess()) {
				List<String> deviceNames = new ArrayList<String>();
				deviceNames.add(deviceName);
				PropertiesSetFlowModel propertiesSetFlowModel = new PropertiesSetFlowModel();
				propertiesSetFlowModel.setProductKey(productKey);
				propertiesSetFlowModel.setDeviceNames(deviceNames);
				propertiesSetFlowModel.setMessageId(response.getData().getMessageId());
				propertiesSetFlowModel.setStatus("0");
				propertiesSetFlowModel.setCreateTime(new Timestamp(new Date().getTime()));
				propertiesSetFlowService.insertPropertiesSet(propertiesSetFlowModel);
				propertiesSetService.insertPropertiesSet(new PropertiesSetModel(propertiesSetFlowModel));
			}
			logger.info(response.getSuccess().toString());
			logger.info(response.getErrorMessage());
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("设备属性设置失败");
			logger.error("-----------设备属性设置异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("设备属性设置失败");
			logger.error("-----------设备属性设置异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public SetDevicePropertyResponse  setDevicesProperty(PropertiesSetModel propertiesSetModel) {

		SetDevicePropertyResponse  response = new SetDevicePropertyResponse ();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		List<String> deviceNames = propertiesSetModel.getDeviceNames();
		/** 属性值 */
		String items = propertiesSetModel.toJSON();
		
		if(deviceNames == null || deviceNames.size()== 0 || deviceNames.size() > 100) {
			response.setSuccess(false);
			response.setErrorMessage("设备不能为空且不能超过100个");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(items)) {
			response.setSuccess(false);
			response.setErrorMessage("items不能为空");
			return response;
		}
		
		if(deviceNames != null && deviceNames.size() >0) {
			for(int i=0;i<deviceNames.size();i++) {
				propertiesSetModel.setDeviceName(deviceNames.get(i));
				response = setDeviceProperty(propertiesSetModel);
				if(response != null && response.getSuccess()) { 
					PropertiesSetFlowModel propertiesSetFlowModel = new PropertiesSetFlowModel();
					propertiesSetFlowModel.setProductKey(productKey);
					propertiesSetFlowModel.setDeviceNames(deviceNames);
					propertiesSetFlowModel.setMessageId(response.getData().getMessageId());
					propertiesSetFlowModel.setStatus("0");
					propertiesSetFlowModel.setCreateTime(new Timestamp(new Date().getTime()));
					propertiesSetFlowService.insertPropertiesSet(propertiesSetFlowModel);
					propertiesSetService.insertPropertiesSet(new PropertiesSetModel(propertiesSetFlowModel));
				}
					
			}
		}
		 
		return response;
	}

	@Override
	public InvokeThingServiceResponse invokeThingService(DeviceModel deviceModel) {

		InvokeThingServiceResponse response = new InvokeThingServiceResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** 物联网设备唯一标识 */
		String iotId = deviceModel.getIotId();
		/** 服务启用参数 */
		String args = deviceModel.getArgs();
		
		if(StringUtils.isNullOrEmpty(iotId)
				&& (StringUtils.isNullOrEmpty(productKey) || StringUtils.isNullOrEmpty(deviceName))) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者productKey与deviceName都不为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(deviceModel.getModuleName())) {
			response.setSuccess(false);
			response.setErrorMessage("模块名称不能为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(deviceModel.getServiceName())) {
			response.setSuccess(false);
			response.setErrorMessage("服务名称不能为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(args)) {
			response.setSuccess(false);
			response.setErrorMessage("服务启用参数不能为空");
			return response;
		}
		
		InvokeThingServiceRequest request = new InvokeThingServiceRequest();  
		request.setArgs(deviceModel.getArgs());
		request.setIdentifier(deviceModel.getModuleName()+":"+deviceModel.getServiceName()); 
		request.setProductKey(productKey);
		request.setDeviceName(deviceName); 
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("调用服务失败");
			logger.error("-----------调用服务异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("调用服务失败");
			logger.error("-----------调用服务异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public InvokeThingsServiceResponse invokeThingsService(DeviceModel deviceModel) {
		
		InvokeThingsServiceResponse response = new InvokeThingsServiceResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		List<String> deviceNames = deviceModel.getDeviceNames();
		/** 模块名称 */
		String moduleName = deviceModel.getModuleName();
		/** 服务名称 */
		String serviceName = deviceModel.getServiceName();
		/** 服务启用参数 */
		String args = deviceModel.getArgs();
		
		if(deviceNames == null || deviceNames.size() > 100) {
			response.setSuccess(false);
			response.setErrorMessage("设备不能为空且不能超过100个");
			return response;
		} 
		
		if(StringUtils.isNullOrEmpty(moduleName)) {
			response.setSuccess(false);
			response.setErrorMessage("模块名称不能为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(serviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("服务名称不能为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(args)) {
			response.setSuccess(false);
			response.setErrorMessage("服务启用参数不能为空");
			return response;
		}
		
		
		InvokeThingsServiceRequest request = new InvokeThingsServiceRequest();
		request.setProductKey(productKey);
		request.setDeviceNames(deviceNames);
		request.setArgs(deviceModel.getArgs());
		request.setIdentifier(deviceModel.getModuleName()+":"+deviceModel.getServiceName()); 
		
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("调用服务失败");
			logger.error("-----------调用服务异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("调用服务失败");
			logger.error("-----------调用服务异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, StringUtils.join(",",deviceNames), response.getSuccess());
		return response;
	}

	@Override
	public SetDeviceDesiredPropertyResponse setDeviceDesiredProperty(DeviceModel deviceModel) {
		
		SetDeviceDesiredPropertyResponse response = new SetDeviceDesiredPropertyResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** 属性值 */
		String items = deviceModel.getItems();
		/** 物联网设备唯一标识 */
		String iotId = deviceModel.getIotId();
		
		if(StringUtils.isNullOrEmpty(iotId)
				&& (StringUtils.isNullOrEmpty(productKey) || StringUtils.isNullOrEmpty(deviceName))) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者productKey与deviceName都不为空");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(items)) {
			response.setSuccess(false);
			response.setErrorMessage("items不能为空");
			return response;
		}
		
		SetDeviceDesiredPropertyRequest request = new SetDeviceDesiredPropertyRequest();
		request.setProductKey(productKey);
		request.setDeviceName(deviceName);
		request.setItems(items);
		request.setIotId(iotId);
		
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("设备属性预设置失败");
			logger.error("-----------设备属性预设置异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("设备属性预设置失败");
			logger.error("-----------设备属性预设置异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public QueryDeviceDesiredPropertyResponse queryDeviceDesiredProperty(DeviceModel deviceModel) {
		
		QueryDeviceDesiredPropertyResponse response = new QueryDeviceDesiredPropertyResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** 物联网设备唯一标识 */
		String iotId = deviceModel.getIotId();
		/** 模块名称 */
		String moduleName = deviceModel.getModuleName();
		/** 要查询属性 */
		List<String> identifiers = deviceModel.getIdentifiers();
		
		if(StringUtils.isNullOrEmpty(iotId)
				&& (StringUtils.isNullOrEmpty(productKey) || StringUtils.isNullOrEmpty(deviceName))) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者productKey与deviceName都不为空");
			return response;
		}
		
		if(identifiers != null && identifiers.size() > 10) {
			response.setSuccess(false);
			response.setErrorMessage("查询属性不能超过10个");
			return response;
		}
		
		if(StringUtils.isNullOrEmpty(deviceModel.getServiceName())) {
			response.setSuccess(false);
			response.setErrorMessage("服务名称不能为空");
			return response;
		}
		 
		QueryDeviceDesiredPropertyRequest request = new QueryDeviceDesiredPropertyRequest();  
		request.setIdentifiers(identifiers); 
		request.setProductKey(productKey);
		request.setDeviceName(deviceName); 
		request.setIotId(iotId);
		request.setFunctionBlockId(moduleName);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询预设置属性失败");
			logger.error("-----------查询预设置属性异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询预设置属性失败");
			logger.error("-----------查询预设置属性异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}

	@Override
	public QueryDevicePropertyStatusResponse queryDevicePropertyStatus(DeviceModel deviceModel) {

		QueryDevicePropertyStatusResponse response = new QueryDevicePropertyStatusResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称 */
		String deviceName = deviceModel.getDeviceName();
		/** 物联网设备唯一标识 */
		String iotId = deviceModel.getIotId();
		/** 模块名称 */
		String moduleName = deviceModel.getModuleName();
		
		if(StringUtils.isNullOrEmpty(iotId)
				&& StringUtils.isNullOrEmpty(deviceName)) {
			response.setSuccess(false);
			response.setErrorMessage("请保证iotId不为空或者deviceName不为空");
			return response;
		}
		
		QueryDevicePropertyStatusRequest request = new QueryDevicePropertyStatusRequest(); 
		request.setProductKey(productKey);
		request.setDeviceName(deviceName); 
		request.setIotId(iotId);
		request.setFunctionBlockId(moduleName);
		 
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
		} catch (ServerException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询设备状态失败");
			logger.error("-----------查询设备状态异常--------------------------",e);
		} catch (ClientException e) {
			response.setSuccess(false);
			response.setErrorMessage("查询设备状态失败");
			logger.error("-----------查询设备状态异常--------------------------",e);
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, deviceName, response.getSuccess());
		return response;
	}



	@Override
	public BatchRegisterDeviceWithApplyIdResponse batchRegisterDeviceWithApplyId(DeviceModel deviceModel) {
		
		/** 调用该接口在指定产品下批量自定义设备名称  */
		BatchCheckDeviceNamesResponse batchCheckDeviceNamesResponse = batchCheckDeviceNames(deviceModel);
		BatchRegisterDeviceWithApplyIdResponse batchRegisterDeviceWithApplyIdResponse = 
				new BatchRegisterDeviceWithApplyIdResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称数组 */
		List<String> deviceNames = deviceModel.getDeviceNames();
		
		if(batchCheckDeviceNamesResponse.getSuccess()) {
			/** 申请批次ID */
			Long applyId = batchCheckDeviceNamesResponse.getData().getApplyId();
			if(applyId != null) {
				deviceModel.setApplyId(applyId);
				deviceModel.setStatus("CHECK");
				QueryBatchRegisterDeviceStatusResponse queryBatchRegisterDeviceStatusResponse = queryBatchRegisterDeviceStatus(deviceModel);
				if(queryBatchRegisterDeviceStatusResponse.getSuccess()) {
					String struts = queryBatchRegisterDeviceStatusResponse.getData().getStatus();
					if("CHECK_SUCCESS".equals(struts)) {
						BatchRegisterDeviceWithApplyIdRequest request = new BatchRegisterDeviceWithApplyIdRequest();
						request.setApplyId(applyId);
						request.setProductKey(productKey);
						try {
							batchRegisterDeviceWithApplyIdResponse = getDefaultAcsClient().getAcsResponse(request);
							if(batchRegisterDeviceWithApplyIdResponse.getSuccess()) {
								/** 查询创建结果 */
								deviceModel.setStatus("CREATE");
								queryBatchRegisterDeviceStatusResponse = queryBatchRegisterDeviceStatus(deviceModel);
								if(queryBatchRegisterDeviceStatusResponse.getSuccess()) {
									if("CREATE_SUCCESS".equals(queryBatchRegisterDeviceStatusResponse.getData().getStatus())){
										DeviceStateModel deviceStateModel = new DeviceStateModel();
										deviceStateModel.setDeviceNames(deviceNames);
										deviceStateModel.setProductKey(productKey);
										deviceStateModel.setState(DeviceStateEnum.NOT_ACTIVE.getCode());
										deviceStateService.batchInsertDeviceState(deviceStateModel);
									}else {
										batchRegisterDeviceWithApplyIdResponse.setErrorMessage("注册失败");
										batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
									}
								}else {
									batchRegisterDeviceWithApplyIdResponse.setErrorMessage("注册失败");
									batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
								}
							}else {
								batchRegisterDeviceWithApplyIdResponse.setErrorMessage("注册失败");
								batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
							}
						} catch (ServerException e) {
							batchRegisterDeviceWithApplyIdResponse.setErrorMessage("注册失败");
							batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
							e.printStackTrace();
						} catch (ClientException e) {
							batchRegisterDeviceWithApplyIdResponse.setErrorMessage("注册失败");
							batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
						}
					}else {
						batchRegisterDeviceWithApplyIdResponse.setErrorMessage("设备名称校验失败");
						batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
					}
				}else {
					batchRegisterDeviceWithApplyIdResponse.setErrorMessage("设备名称校验失败");
					batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
				} 
			}else {
				batchRegisterDeviceWithApplyIdResponse.setErrorMessage("系统异常");
				batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
			}
		}else {
			batchRegisterDeviceWithApplyIdResponse.setErrorMessage(batchCheckDeviceNamesResponse.getErrorMessage());
			batchRegisterDeviceWithApplyIdResponse.setSuccess(false);
		}
		return batchRegisterDeviceWithApplyIdResponse;
	}



	@Override
	public BatchCheckDeviceNamesResponse batchCheckDeviceNames(DeviceModel deviceModel) {

		BatchCheckDeviceNamesResponse response = new BatchCheckDeviceNamesResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 设备名称数组 */
		List<String> deviceNames = deviceModel.getDeviceNames();
		/** 设备昵称数组 */
		List<String> nickNames = deviceModel.getNickNames();
		 
		if(nickNames != null && nickNames.size() > 10000) {
			response.setSuccess(false);
			response.setErrorMessage("设备昵称不能超过10000个");
			return response;
		}
		
		if(deviceNames == null || deviceNames.size() ==0
				|| deviceNames.size() >10000) {
			response.setSuccess(false);
			response.setErrorMessage("设备名称不能为空，且不能超过10000个");
			return response;
		}
		 
		BatchCheckDeviceNamesRequest request = new BatchCheckDeviceNamesRequest(); 
		List<BatchCheckDeviceNamesRequest.DeviceNameList> deviceNameLists 
			= new ArrayList<BatchCheckDeviceNamesRequest.DeviceNameList>();
		if(deviceNames != null && nickNames != null
				&& deviceNames.size() == nickNames.size()) {
			int length = deviceNames.size();
			for(int i = 0; i< deviceNames.size(); i++) {
				BatchCheckDeviceNamesRequest.DeviceNameList deviceNameList = 
						new BatchCheckDeviceNamesRequest.DeviceNameList();
				deviceNameList.setDeviceName(deviceNames.get(i));
				deviceNameList.setDeviceNickname(nickNames.get(i));
				deviceNameLists.add(deviceNameList);
			}
			request.setDeviceNameLists(deviceNameLists);
		}else {
			request.setDeviceNames(deviceNames); 
		}
		request.setProductKey(productKey);
		 
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			logger.info(response.getSuccess().toString());
			logger.info(response.getErrorMessage());
		} catch (ServerException e) {
			response.setSuccess(false);
			e.printStackTrace();
		} catch (ClientException e) {
			response.setSuccess(false);
			e.printStackTrace();
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, StringUtils.join(",",deviceNames), response.getSuccess());
		return response;
	}



	@Override
	public QueryBatchRegisterDeviceStatusResponse queryBatchRegisterDeviceStatus(DeviceModel deviceModel) {

		QueryBatchRegisterDeviceStatusResponse response = new QueryBatchRegisterDeviceStatusResponse();
		/** 产品key */
		String productKey = aliyunConfig.productKey;
		/** 申请批次ID */
		Long applyId = deviceModel.getApplyId();
		/** 类别 */
		String registerStatus = deviceModel.getStatus();
		QueryBatchRegisterDeviceStatusRequest request = new QueryBatchRegisterDeviceStatusRequest(); 
		request.setApplyId(applyId);
		request.setProductKey(productKey);
		Date requestTime = null;
		Date responseTime = null;
		try {
			requestTime = new Date();
			response = getDefaultAcsClient().getAcsResponse(request);
			responseTime = new Date();
			if(response.getSuccess()) {
				String struts = response.getData().getStatus();
				while (registerStatus.equals(struts)){
					try {
			            Thread.sleep(1000); //1000 毫秒，也就是1秒.
			            /** 创建中 */
						response = getDefaultAcsClient().getAcsResponse(request);
						if(response.getSuccess()) {
							struts = response.getData().getStatus();
						}else {
							break;
						}
		            } catch(InterruptedException ex) {
		            	Thread.currentThread().interrupt();
		            }
				}
			}
			logger.info(response.getSuccess().toString());
			logger.info(response.getErrorMessage());
		} catch (ServerException e) {
			response.setSuccess(false);
			e.printStackTrace();
		} catch (ClientException e) {
			response.setSuccess(false);
			e.printStackTrace();
		}
		this.addAliyunApiLog(request, requestTime, response, responseTime, productKey, "", response.getSuccess());
		return response;
	}
}
